#include <QUrl>
#include <QByteArray>
#include <QtScript/QScriptValueIterator>
#include <QDebug>

#include "commentmanager.h"
#include "cvsession.h"
#include "util/cvutil.h"
#include "http/cvhttp.h"

CommentManager::CommentManager(QObject *parent) :
    QObject(parent)
{
}

void CommentManager::getBlogComments(const QString &blogId, int limit, int offset)
{
    QUrl url = CVUtil::getBaseUrl("blogs.get_comments_by_blog");
    url.addQueryItem("blog_id", blogId);
    url.addQueryItem("limit", QString::number(limit));
    url.addQueryItem("offset", QString::number(offset));
    CVHttp *http = new CVHttp(url);
    //http->setDebug(true);
    connect(http, SIGNAL(finished(QScriptValue,QString)),
            this, SLOT(parseData(QScriptValue,QString)));
}

void CommentManager::getTopicComments(const QString &topicId, int limit, int offset)
{
    QUrl url = CVUtil::getBaseUrl("forums.get_comments");
    url.addQueryItem("topic_id", topicId);
    url.addQueryItem("limit", QString::number(limit));
    url.addQueryItem("offset", QString::number(offset));
    CVHttp *http = new CVHttp(url);
    http->setDebug(true);
    connect(http, SIGNAL(finished(QScriptValue,QString)),
            this, SLOT(parseData(QScriptValue,QString)));
}

void CommentManager::parseData(QScriptValue json, const QString &msg)
{
    QList<Comment *> *comments = new QList<Comment *>();
    if (!json.isNull() && !json.isError())
    {
        if (json.isArray())
        {
            QScriptValueIterator it(json);
            while (it.hasNext())
            {
                it.next();
                QScriptValue value = it.value();
                if (value.property("id").toString().isEmpty())
                {
                    continue;
                }
                Comment *comment = new Comment();
                comment->setId(value.property("id").toString());
                QString desc = value.property("desc").toString();
                if (desc.isEmpty())
                {
                    // topic
                    desc = value.property("message").toString();
                }
                comment->setCommentText(desc);
                QString owner = value.property("owner").toString();
                if (owner.isEmpty())
                {
                    owner = value.property("owner_id").toString();
                }
                comment->setOwner(owner);
                comment->setOwnerIcon(value.property("owner_icon").toString());
                comment->setTimeCreated(value.property("time_created").toString());
                comments->append(comment);
            }
        }
    }

    emit handleComments(comments);
}
